package com.lxl.bt.util;

import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.PathEffect;
import android.graphics.Rect;
import android.view.View;

import androidx.recyclerview.widget.RecyclerView;

/**
 * @Author : xinlong.lv
 */
public class BrokenDividerDecoration extends RecyclerView.ItemDecoration {

    //分割线的默认高度
    private float mDividerHeight = 4;
    //画分割线的画笔
    private Paint mPaint;
    //左右偏移量
    private float margin = 0;
    //float数组的四个数是指的先画15px的实线，然后画10px的空白再画15px的实线，再画10px的空白...一次规律循环。后面的“5”指的是第一条实线要距离开始位置多远。
    PathEffect effects = new DashPathEffect(new float[]{15, 10, 15, 10}, 5);
    public BrokenDividerDecoration() {
        mPaint = new Paint();
        // 开启抗锯齿效果
        mPaint.setAntiAlias(true);
        //设置分割线默认的颜色
        mPaint.setColor(Color.GRAY);
        mPaint.setPathEffect(effects);
    }

    public BrokenDividerDecoration(int color, float height) {
        mPaint = new Paint();
        // 开启抗锯齿效果
        mPaint.setAntiAlias(true);
        //设置分割线默认的颜色
        mPaint.setColor(color);
        mPaint.setPathEffect(effects);
        this.mDividerHeight = height;
    }

    //设置分割线左右偏移量
    public BrokenDividerDecoration setMargin(float margin) {
        this.margin = margin;
        return this;
    }

    public BrokenDividerDecoration setColor(int color) {
        mPaint.setColor(color);
        return this;
    }

    public BrokenDividerDecoration setDividerHeight(float height) {
        this.mDividerHeight = height;
        return this;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);
        //第一个 ItemView 不需要绘制
        if (parent.getChildAdapterPosition(view) != 0) {
            //指相对itemView顶部的偏移量
            outRect.top = (int) mDividerHeight;
        }
    }

    @Override
    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
        super.onDraw(c, parent, state);

        int childCount = parent.getChildCount();
        //因为 getItemOffsets 是针对每一个 ItemView ，而 onDraw 方法是针对 RecyclerView 本身，所以需要循环遍历来设置
        for (int i = 0; i < childCount; i++) {
            View view = parent.getChildAt(i);
            int index = parent.getChildAdapterPosition(view);
            //第一个 ItemView 不需要绘制
            if (index == 0) {
                continue;//跳过本次循环体中尚未执行的语句，立即进行下一次的循环条件判断
            }
            float dividerTop = view.getTop() - mDividerHeight;
            float dividerLeft = parent.getPaddingLeft() + margin;
            float dividerBottom = view.getTop();
            float dividerRight = parent.getWidth() - parent.getPaddingRight() - margin;
            c.drawRect(dividerLeft, dividerTop, dividerRight, dividerBottom, mPaint);
        }
    }
}
